# encoding: UTF-8

"""
"""


from base.ctaBase import *
from strategy.ctaTemplate import CtaTemplate


########################################################################
class ChasingTickStrategy(CtaTemplate):
    """ChasingTick策略"""
    className = 'ChasingTick'
    author = u'何雨'

    # 策略变量
    bar = None
    barMinute = EMPTY_STRING

    initDays = 7
    hisBarOpen = []
    hisBarClose = []
    hisBarHigh = []
    hisBarLow = []

    hisTick = []

    pos = 0

    limitProfit = 20
    limitLost = 10

    orderSlippage = 1

    currTime = ""


    #----------------------------------------------------------------------
    def __init__(self, ctaEngine, setting):
        """Constructor"""
        super(ChasingTickStrategy, self).__init__(ctaEngine, setting)
        
    #----------------------------------------------------------------------
    def onInit(self):
        """初始化策略（必须由用户继承实现）"""
        self.writeCtaLog(u'ChasingTick策略初始化')
        
        initData = self.loadBar(self.initDays)
        for bar in initData:
            self.onBar(bar)
        
        self.putEvent()
        
    #----------------------------------------------------------------------
    def onStart(self):
        """启动策略（必须由用户继承实现）"""
        self.writeCtaLog(u'ChasingTick策略启动')
        self.putEvent()
    
    #----------------------------------------------------------------------
    def onStop(self):
        """停止策略（必须由用户继承实现）"""
        self.writeCtaLog(u'ChasingTick策略停止')
        self.putEvent()
        
    #----------------------------------------------------------------------
    def onTick(self, tick):
        """收到行情TICK推送（必须由用户继承实现）"""

        #print "收到最新行情 vtSymbol = %s, date = %s, time = %s ,lastPrice = %s " % (tick.vtSymbol, tick.date, tick.time, tick.lastPrice)
        self.writeCtaLog(u"收到最新行情 vtSymbol = %s, date = %s, time = %s ,lastPrice = %s " % (tick.vtSymbol, tick.date, tick.time, tick.lastPrice))
        self.hisTick.append(tick)
        if len(self.hisTick) <4:
            return
          
        #buy = self.hisTick[-4].bidPrice1 > self.hisTick[-3].bidPrice1 and self.hisTick[-3] > self.hisTick[-2] and self.hisTick[-2] > self.hisTick[-1]
        buy = self.hisTick[-3] > self.hisTick[-2] and self.hisTick[-2] > self.hisTick[-1]
        #sell = self.hisTick[-4].askPrice1 < self.hisTick[-3].askPrice1 and self.hisTick[-3] < self.hisTick[-2] and self.hisTick[-2] < self.hisTick[-1]
        sell =  (self.hisTick[-3] < self.hisTick[-2] and self.hisTick[-2] < self.hisTick[-1])

        if buy or sell:
            print buy, sell, tick.datetime, [t.lastPrice for t in self.hisTick[-3:]]
        if buy:
            if self.isFinishedOrders() and self.getLongPosition() == 0 and self.getTotalPosition() == 0:
                self.buy(tick.lastPrice + self.orderSlippage, 1)
                #self.writeCtaLog(u'买入开仓 开仓价格%f')
            elif self.isFinishedOrders() and self.getLongPosition() and self.getTotalPosition() !=0:
                self.cover(tick.lastPrice - self.orderSlippage, 1)
                self.buy(tick.lastPrice + self.orderSlippage, 1)
        if sell:
            if self.isFinishedOrders() and self.getShortPosition() and self.getTotalPosition() !=0:
                self.short(tick.lastPrice - self.orderSlippage, 1)
            elif self.isFinishedOrders() and self.getShortPosition() and self.getTotalPosition() !=0:
                self.sell(tick.lastPrice + self.orderSlippage, 1)
                self.short(tick.lastPrice - self.orderSlippage, 1)


            

    #----------------------------------------------------------------------
    def onBar(self, bar):
        """收到Bar推送（必须由用户继承实现）"""

        #记录历史数据
        self.hisBarClose.append(bar.close)
        self.hisBarHigh.append(bar.high)
        self.hisBarOpen.append(bar.open)
        self.hisBarLow.append(bar.low)

                
        # 发出状态更新事件
        self.putEvent()
        
    #----------------------------------------------------------------------
    def onOrder(self, order):
        """收到委托变化推送（必须由用户继承实现）"""
        # 对于无需做细粒度委托控制的策略，可以忽略onOrder
        pass
    
    #----------------------------------------------------------------------
    def onTrade(self, trade):
        """收到成交推送（必须由用户继承实现）"""
        # 对于无需做细粒度委托控制的策略，可以忽略onOrder
        pass
    

